const { spawn } = require('child_process');
const fs = require('fs-extra');
const path = require('path');
let { processRestartTime = 20 } = require('../config/config.json');
const Logger = require('../Logger');

function startProcess() {
	const child = spawn('node', ['script/debug.js']);

	child.on('exit', (code) => {
		processRestartTime--;

		if (processRestartTime < 0) {
			console.log('已经重启' + processRestartTime + '次了');

			return;
		}
		if (code !== 0) {
			console.log('程序崩溃， 自动重启中');
			Logger.log('程序崩溃， 自动重启中 \n');

			startProcess(); // 重新启动进程
		}
	});
}

startProcess(); // 初始启动进程

/**
 * 进程崩溃日志记录
 */
(function trackCrash(pathname) {
	fs.ensureFileSync(pathname);

	const messageList = [
		`PID: ${process.pid}`,
	];

	function retreat(error) {
		messageList.push(`\n${error.stack}`);
		fs.writeFileSync(pathname, messageList.join('\n'));
		throw error;
	}

	process
		.on('uncaughtException', function handleError(error) {
			messageList.unshift('uncaughtException:');
			retreat(error);
		})
		.on('unhandledRejection', function handleRejection(error) {
			messageList.unshift('unhandledRejection:');
			retreat(error);
		});
})(path.join(process.cwd(), 'logs', 'crash.log'));